<template>
	<view class="form">
		<uni-forms ref="valiForm" :rules="rules" :model="FormData" labelWidth="60px">
			<uni-forms-item label="标题" required name="title">
				<uni-easyinput :inputBorder='false' v-model="FormData.title" placeholder="请输入标题" />
			</uni-forms-item>
			<uni-forms-item label="类型" required name="type">
				<!-- <uni-data-select :inputBorder='false' v-model="FormData.type" :localdata="typeList">
				</uni-data-select> -->
				<uni-data-picker placeholder="请选择分类" popup-title="请选择分类" :localdata="typeList" v-model="FormData.type"
					:map="props" @change="onchange" @nodeclick="onnodeclick" @popupopened="onpopupopened"
					@popupclosed="onpopupclosed">
				</uni-data-picker>
			</uni-forms-item>
			<uni-forms-item label="位置" required name="location">
				<view style="display: flex; justify-content: space-between; align-items: center;">
					<text>{{FormData.location}}</text>
					<button size="mini" style="padding:0 5px; width: 80px;" type="primary"
						@click="getLocation()">获取位置</button>
				</view>
			</uni-forms-item>
			<uni-forms-item label="描述">
				<uni-easyinput maxlength="2000" :inputBorder='false' autoHeight type="textarea"
					v-model="FormData.description" placeholder="请输入描述" />
			</uni-forms-item>
			<view class="takephoto">
				<uni-file-picker ref="imageUpload" @select="select" @delete="deleteimg" limit="9" fileMediatype="image"
					v-model="imageValue" file-extname="png,jpg">
					<view class="takephoto">
						<uni-icons type="camera" color="#00B5DD" size="28"></uni-icons>
						<text>添加图片</text>
					</view>
				</uni-file-picker>
			</view>
			<view class="tips">
				<view class="example">
					<view>
						<text class="title">拍摄提示</text>
						<text class="text">请按照***角度、***仰角进行拍照，若为鱼塘请拍四个角</text>
					</view>
					<view>
						<image class="image" mode="aspectFill"
							src="https://staticfile-yj.obs.cn-north-4.myhuaweicloud.com/yutang.jpg"></image>
					</view>
				</view>
				<view>
					<text class="text">温馨提示：拍摄完成后相关农田、鱼塘等基本信息、拍摄时间、拍摄位置、当时温湿(若鱼塘的话则会上传鱼塘的温度等信息)将会上传至相关机构</text>
				</view>
			</view>
			<button class="customer-btn" @click="submit(FormData)">保存并发布</button>
		</uni-forms>
	</view>
</template>

<script>
	import {
		baseurl,
		queryDictDataTree,
		addSnapshot,
		batchUploadFile,
		uploadFile,
		queryLocation,
		querySnapshotDetail,
		updateSnapshot
	} from "@/api/user.js"
	export default {
		data() {
			return {
				FormData: {
					title: '',
					type: '',
					location: '',
					fileIdList: [],
					description: '',
				},
				props: {
					text: 'name',
					value: 'code'
				},
				type: '',
				typeList: [],
				rules: {
					title: {
						rules: [{
							required: true,
							errorMessage: '标题不能为空'
						}]
					},
					type: {
						rules: [{
							required: true,
							errorMessage: '请选择类型'
						}]
					},
					location: {
						rules: [{
							required: true,
							errorMessage: '请选择位置'
						}]
					}
				},
				imageValue: [],
			};
		},
		onLoad: function(options) {
			if (options.id) {
				this.type = "update"
				console.log("options", options);
				this.querySnapshotDetail(options.id)
			}
			this.queryDictDataTree({
				"dictType": 'SNAPSHOT_TYPE'
			})
		},
		methods: {
			async addSnapshot(options) {
				const res = await addSnapshot(options);
				if (res.success) {
					uni.showToast({
						title: '上传成功！'
					})
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/home/home'
						});
					}, 500)
				}
				console.log('uploadFile', res)
			},
			async updateSnapshot(options) {
				const res = await updateSnapshot(options);
				if (res.success) {
					uni.showToast({
						title: '上传成功！'
					})
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/mine/myPhoto/myPhoto'
						});
					}, 500)
				}
				console.log('uploadFile', res)
			},
			async queryDictDataTree(options) {
				const res = await queryDictDataTree(options);
				let temp = JSON.stringify(res.returnObj);
				//temp = temp.replaceAll("subDictDataList", "children")
				temp = temp.replace(/subDictDataList/g, "children")
				this.typeList = JSON.parse(temp)
			},
			async batchUploadFile(options) {
				const res = await batchUploadFile(options);
				console.log('uploadFileRes', res);
				this.FormData.fileIdList = res.returnObj
			},
			async queryLocation(options) {
				const res = await queryLocation(options);
				this.FormData.location = res.returnObj.address
			},

			async querySnapshotDetail(options) {
				const res = await querySnapshotDetail(options);
				this.FormData = res.returnObj
				this.FormData.fileIdList.forEach((el) => {
					let obj = {
						"name": el,
						"extname": el.split('.')[1],
						"url": 'https://nongmao.obs.cn-north-4.myhuaweicloud.com/' + el,
					}
					this.imageValue.push(obj)
				})
				console.log("image", this.imageValue)
			},
			getLocation() {
				const appAuthorizeSetting = uni.getAppAuthorizeSetting()
				console.log("appauthor", appAuthorizeSetting)
				if (appAuthorizeSetting.locationAuthorized == 'authorized') {
					uni.getLocation({
						type: 'wgs84'
					}).then((res) => {
						console.log(res)
						this.queryLocation({
							lat: res[1].latitude,
							lng: res[1].longitude
						})
					})
				} else {
					uni.openAppAuthorizeSetting({
						success(res) {
							console.log(res)
						}
					})
				}
			},
			select(e) {
				console.log("selecte", e)
				console.log("imagevalue", this.imageValue)
				const tempFilePaths = e.tempFilePaths;
				tempFilePaths.forEach((i) => {
					uni.uploadFile({
						url: "https://1yj-rt.gfox.ltd/nongmao/nb-as/1.0.1/FileService/uploadFile",
						filePath: i,
						name: 'file',
						header: {
							'Cookie': `X-Token=${uni.getStorageSync('X-Token')}`,
							'Content-Type': 'multipart/form-data'
						},
						success: (uploadFileRes) => {
							console.log('uploadFileRes', uploadFileRes.data);
							const res = uploadFileRes.data
							this.FormData.fileIdList.push(JSON.parse(res).returnObj);
							//处理数据
							//const path=JSON.parse(uploadFileRes.data)
							//赋值，前端渲染
							//this.baseFormData.photo=path.imgUrl
						},
						fail: (err) => {
							console.log('err')
						},
						complete: () => {}
					})
					//获取图片临时路径
					//const imgUrl = tempFilePaths[0];
					//console.log('tempFilePaths',tempFilePaths)
					//this.batchUploadFile(tempFilePaths);
				})

			},
			deleteimg(e) {
				console.log("delete", e)
				this.FormData.fileIdList.forEach((el, index) => {
					if (el == e.tempFile.name) {
						this.FormData.fileIdList.splice(index, 1)
					}
				})
				console.log(this.FormData.fileIdList)
			},
			submit(ref) {
				this.$refs['valiForm'].validate().then(res => {
					let tempobj = ref;
					if (this.type == "update") {
						this.updateSnapshot(tempobj)
					} else {
						this.addSnapshot(tempobj);
					}

				}).catch(err => {
					console.log('err', err);
				})
			},
			onnodeclick(e) {
				console.log(e);
			},
			onpopupopened(e) {
				console.log('popupopened');
			},
			onpopupclosed(e) {
				console.log('popupclosed');
			},
			onchange(e) {
				console.log('onchange:', e);
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #fff;
	}

	.takephoto {
		border-radius: 8px;
		background-color: #F4F5F6;
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.file-picker__box {
		width: 100% !important;
		height: 116px !important;
	}

	.tips {
		background-color: #F5F8FB;
		border-radius: 8px;
		padding: 32rpx;
		margin: 16px 0;

		.example {
			display: flex;
			flex-flow: row nowrap;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 15px;

			.image {
				box-sizing: border-box;
				width: 212rpx;
				max-height: 77px;
				background-image: url('https://staticfile-yj.obs.myhuaweicloud.com/other-box.png');
				background-repeat: no-repeat;
				background-size: 100% 100%;
				padding: 10px;
			}

			.title {
				display: block;
				height: 22px;
				line-height: 22px;
				margin-bottom: 8px;
				color: #283241;
				font-size: 28rpx;
				font-weight: bold;
			}


		}

		.text {
			line-height: 22px;
			color: #646A74;
			font-size: 28rpx;
		}
	}

	.customer-btn {
		background-color: #00B5DD !important;
		color: #fff;
		border-radius: 8px;
		height: 44px;
		line-height: 44px;
		font-size: 32rpx;
		font-weight: 500;
	}
</style>